package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;

import cn.wolfcode.crm.query.JsonResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;


    @RequiresPermissions(value = {"department:list","部门列表"},logical = Logical.OR)
    @RequestMapping("/list")
    //@RequiredPermission(name = "部门列表",expression = "department:list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Department> pageResult = departmentService.query(qo);
        model.addAttribute("result",pageResult);
        return "department/list";
    }
    // 查询所有请求信息
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    //@RequiredPermission(name = "部门删除",expression = "department:delete")
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                departmentService.delete(id);
                return new JsonResult(true,"删除成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(true,"删除失败");
    }
    // 添加新的信息


    // 添加新的信息
    @RequiredPermission(name = "部门添加",expression = "department:input")
    @RequestMapping("/input")
    public String input(Model model,Long id){
        // 如果 id 不为空,携带该 id 对应的数据过 input 视图
        if (id != null) {
            model.addAttribute("department",departmentService.get(id));
        }
        // 跳转到 input 视图
        return "department/input";
    }

    // 添加 或 修改 信息
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "部门添加或修改",expression = "department:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department department){
        try {
            if (department.getId() != null) {
                // 如果 id 不为空,调用 修改方法
                departmentService.update(department);
            }else {
                // 如果 id 为空,调用保存方法
                departmentService.save(department);
            }
            return new JsonResult(true,"操作成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(false,"操作失败");

    }
}
